from fastapi import FastAPI, Request, Response, HTTPException, status
from fastapi.staticfiles import StaticFiles
from starlette.responses import RedirectResponse, JSONResponse
from starlette.middleware.sessions import SessionMiddleware
import httpx
import os
import json
from dotenv import load_dotenv # 导入 load_dotenv

# 加载 .env 文件中的环境变量
load_dotenv()

app = FastAPI()

# 从环境变量获取微信配置，或者使用默认值（仅用于开发测试）
WECHAT_APP_ID = os.getenv("WECHAT_APP_ID", "YOUR_WECHAT_APP_ID")
WECHAT_APP_SECRET = os.getenv("WECHAT_APP_SECRET", "YOUR_WECHAT_APP_SECRET")
SESSION_SECRET_KEY = os.getenv("SESSION_SECRET_KEY", "super-secret-key") # 生产环境请务必使用强随机密钥
print(f"SESSION_SECRET_KEY: {SESSION_SECRET_KEY}")
print(f"WECHAT_APP_ID: {WECHAT_APP_ID}")

# 添加 SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET_KEY)

# 将静态文件目录挂载到 /rzwl/static 路径
app.mount("/rzwl/static", StaticFiles(directory="backend/static"), name="static")

@app.get("/rzwl")
async def read_root():
    return RedirectResponse(url="/rzwl/static/index.html")

# 微信网页授权回调接口
@app.get("/rzwl/wechat_oauth_callback")
async def wechat_oauth_callback(request: Request, code: str = None, state: str = None):
    if not code:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing code parameter")

    # 1. 通过 code 换取 access_token 和 openid
    token_url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={WECHAT_APP_ID}&secret={WECHAT_APP_SECRET}&code={code}&grant_type=authorization_code"
    async with httpx.AsyncClient() as client:
        response = await client.get(token_url)
        token_info = response.json()

    if "errcode" in token_info:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=token_info.get("errmsg", "WeChat OAuth error"))

    openid = token_info.get("openid")
    access_token = token_info.get("access_token")

    if not openid:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to get OpenID from WeChat")

    # 2. 将 openid 存储到会话中
    request.session["openid"] = openid
    request.session["access_token"] = access_token # 可选：存储 access_token

    # 3. 重定向回原页面或指定页面
    redirect_url = request.session.pop("redirect_after_login", "/rzwl/static/index.html")
    return RedirectResponse(url=redirect_url, status_code=status.HTTP_302_FOUND)

# 检查登录状态接口
@app.get("/rzwl/check_login_status")
async def check_login_status(request: Request):
    openid = request.session.get("openid")
    if openid:
        return JSONResponse({"logged_in": True, "openid": openid})
    return JSONResponse({"logged_in": False})

# 需要登录的页面路由
@app.get("/rzwl/enroll")
async def read_enroll(request: Request):
    if "openid" not in request.session:
        # 如果未登录，保存当前页面路径并重定向到微信授权
        request.session["redirect_after_login"] = "/rzwl/static/enroll.html"
        wechat_oauth_url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={WECHAT_APP_ID}&redirect_uri={request.url.scheme}://{request.url.netloc}/rzwl/wechat_oauth_callback&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        print(f"\n\n\nwechat_oauth_url: {wechat_oauth_url}")
        return RedirectResponse(url=wechat_oauth_url, status_code=status.HTTP_302_FOUND)
    return RedirectResponse(url="/rzwl/static/enroll.html")

@app.get("/rzwl/pay")
async def read_pay(request: Request):
    if "openid" not in request.session:
        request.session["redirect_after_login"] = "/rzwl/static/pay.html"
        wechat_oauth_url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={WECHAT_APP_ID}&redirect_uri={request.url.scheme}://{request.url.netloc}/rzwl/wechat_oauth_callback&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        return RedirectResponse(url=wechat_oauth_url, status_code=status.HTTP_302_FOUND)
    return RedirectResponse(url="/rzwl/static/pay.html")

@app.get("/rzwl/me")
async def read_me(request: Request):
    if "openid" not in request.session:
        request.session["redirect_after_login"] = "/rzwl/static/me.html"
        wechat_oauth_url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={WECHAT_APP_ID}&redirect_uri={request.url.scheme}://{request.url.netloc}/rzwl/wechat_oauth_callback&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        return RedirectResponse(url=wechat_oauth_url, status_code=status.HTTP_302_FOUND)
    return RedirectResponse(url="/rzwl/static/me.html")

@app.get("/rzwl/hello")
async def hello_world():
    return {"message": "Hello from FastAPI with rzwl prefix!"}

# 示例：获取用户 OpenID 的接口（仅用于测试，实际应用中不直接暴露）
@app.get("/rzwl/get_openid")
async def get_openid(request: Request):
    openid = request.session.get("openid")
    if openid:
        return {"openid": openid}
    return {"openid": "未登录"}

# 获取微信 AppID 的接口
@app.get("/rzwl/get_wechat_appid")
async def get_wechat_appid():
    print(f"WECHAT_APP_ID: {WECHAT_APP_ID}")
    return JSONResponse({"appid": WECHAT_APP_ID})
